package org.androidpush.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import org.androidpush.R;
import org.androidpush.activity.ChatActivity;
import org.androidpush.adapter.SortLinkAdapter;
import org.androidpush.client.Constants;
import org.androidpush.client.LogUtil;
import org.androidpush.client.ServiceManager;
import org.androidpush.greendao.ChatMsg;
import org.androidpush.greendao.ChatMsgDao;
import org.androidpush.greendao.UserFriend;
import org.androidpush.greendao.UserFriendDao;
import org.androidpush.ui.SideBar;
import org.androidpush.utils.ConstantUtils;
import org.androidpush.utils.DBUtils;

import java.util.List;


public class LinkFragment extends Fragment {

    private static final String LOGTAG = LogUtil
            .makeLogTag(LinkFragment.class);

    private ListView listView;
    private SortLinkAdapter sortadapter;
    private List<UserFriend> friendDatas;
    private SideBar sidebar;
    private TextView dialog;
    private View view;
    private UserFriendDao userFriendDao;
    private ChatMsgDao chatMsgDao;
    private int msgCount = 0;
    private ChatLinkReceiver chatMsgReceiver;
    private Activity activity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.xml_link, container, false);
        activity = getActivity();
        init();
        setListViewItemOnClickListener();
        return view;
    }

    private void init() {
        userFriendDao = DBUtils.getUserFriendDao(getActivity());
        chatMsgDao = DBUtils.getChatMsgDao(getActivity());
        sidebar = (SideBar) view.findViewById(R.id.id_link_sidebar);
        listView = (ListView) view.findViewById(R.id.id_listview_list);
        dialog = (TextView) view.findViewById(R.id.id_link_dialog);
        sidebar.setTextView(dialog);

        chatMsgReceiver = new ChatLinkReceiver();
        IntentFilter chatfilter = new IntentFilter();
        chatfilter.addAction(Constants.ACTION_SHOW_CHATMSG);
        chatfilter.addAction(Constants.ACTION_CHATMSG_CLICKED);
        chatfilter.addAction(Constants.ACTION_CHATMSG_CLEARED);
        view.getContext().registerReceiver(chatMsgReceiver, chatfilter);
        initData();
    }

    private void initData() {
        friendDatas = userFriendDao.queryBuilder().list();
        if (friendDatas.size() > 0) {
            sortadapter = new SortLinkAdapter(view.getContext(), friendDatas);
            listView.setAdapter(sortadapter);
        }
    }

    private void setListViewItemOnClickListener() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                UserFriend userFriend = null;
                userFriend = friendDatas.get(position);
                msgCount = 0;
                if (userFriend != null) {
                    userFriend.setNewMsgCount(null);
                    friendDatas.remove(position);
                    friendDatas.add(position, userFriend);
                    sortadapter.notifyDataSetChanged();
                    Activity activity = (Activity) view.getContext();
                    Intent intent = new Intent(activity, ChatActivity.class);
                    intent.putExtra(ConstantUtils.FRIEND_ID, userFriend.getFriendId().toString());
                    intent.putExtra(ConstantUtils.FRIEND_NAME, userFriend.getFriendName());
                    intent.putExtra("Activity", true);
                    startActivity(intent);
                    activity.overridePendingTransition(R.anim.push_left_in,
                            R.anim.push_left_out);
                } else {
                    Log.d("User", "UserDto is null");
                }
                return;
            }
        });

        sidebar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                int position = sortadapter.getPositionForSelection(s.charAt(0));

                if (position != -1) {
                    listView.setSelection(position);
                }
            }
        });
    }

    public final class ChatLinkReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(LOGTAG, "ChatLinkReceiver.onReceive()...");
            String action = intent.getAction();
            Log.d(LOGTAG, action);

            if (Constants.ACTION_SHOW_CHATMSG.equals(intent.getAction())) {
                ++msgCount;
                ChatMsg chatMsg = new ChatMsg();
                String chatToUser = intent
                        .getStringExtra(Constants.CHATMSG_TOUSER);
                String chatFromUser = intent
                        .getStringExtra(Constants.CHATMSG_FROMUSER);
                String chatDate = intent
                        .getStringExtra(Constants.CHATMSG_DATE);
                String chatMessage = intent
                        .getStringExtra(Constants.CHATMSG_MESSAGE);
                String chatType = intent
                        .getStringExtra(Constants.CHATMSG_TYPE);
                Log.d(LOGTAG + "Receiver", "chatToUser=" + chatToUser);
                Log.d(LOGTAG + "Receiver", "chatFromUser=" + chatFromUser);
                Log.d(LOGTAG + "Receiver", "chatDate=" + chatDate);
                Log.d(LOGTAG + "Receiver", "chatMessage=" + chatMessage);
                Log.d(LOGTAG + "Receiver", "chatType=" + chatType);
                chatMsg.setUserId(Long.parseLong(chatToUser));
                chatMsg.setFriendId(Long.parseLong(chatFromUser));
                chatMsg.setMessage(chatMessage);
                chatMsg.setDate(chatDate);
                chatMsg.setMsgtype(Boolean.parseBoolean(chatType));

                chatMsgDao = DBUtils.getChatMsgDao((Activity)view.getContext());
                chatMsgDao.insertOrReplace(chatMsg);
                UserFriend userFriend = new UserFriend();
                for(int i = 0;i<friendDatas.size(); i++){
                    UserFriend friend = friendDatas.get(i);
                    if(Long.parseLong(chatFromUser)==friend.getFriendId()){
                        userFriend.setNewMsgCount(Integer.toString(msgCount));
                        userFriend.setFriendName(friend.getFriendName());
                        userFriend.setPinYinName(friend.getPinYinName());
                        userFriend.setFirstPinYin(friend.getFirstPinYin());
                        userFriend.setFriendId(friend.getFriendId());
                        userFriend.setFriendSex(friend.getFriendSex());
                        userFriend.setFriendImg(friend.getFriendImg());
                        Log.d(LOGTAG+"Img", String.valueOf(userFriend.getFriendImg()));
                        friendDatas.remove(i);
                        friendDatas.add(i,userFriend);
                        break;
                    }
                }
                Log.d(LOGTAG,friendDatas.toString());
                sortadapter.notifyDataSetChanged();
                listView.setSelection(listView.getCount()-1);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        view.getContext().unregisterReceiver(chatMsgReceiver);
    }
}
